package ase.eleitweg.client.gui;

import java.io.File;
import java.io.IOException;
import java.rmi.RemoteException;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import org.eclipse.swt.SWT;
import org.eclipse.swt.events.ControlAdapter;
import org.eclipse.swt.events.ControlEvent;
import org.eclipse.swt.events.MouseAdapter;
import org.eclipse.swt.events.MouseEvent;
import org.eclipse.swt.graphics.Cursor;
import org.eclipse.swt.graphics.Image;
import org.eclipse.swt.graphics.Point;
import org.eclipse.swt.layout.*;
import org.eclipse.swt.widgets.Button;
import org.eclipse.swt.widgets.Composite;
import org.eclipse.swt.widgets.Dialog;
import org.eclipse.swt.widgets.Display;
import org.eclipse.swt.widgets.Label;
import org.eclipse.swt.widgets.Shell;

import com.google.inject.Guice;
import com.google.inject.Injector;

import ase.eleitweg.LocalModule;
import ase.eleitweg.TestDBMemoryFilled;
import ase.eleitweg.client.gui.utils.FileByteConverter;
import ase.eleitweg.client.gui.utils.FileHandler;
import ase.eleitweg.common.*;
import ase.eleitweg.server.RunController;
import ase.eleitweg.server.RunManager;
import ase.eleitweg.server.UserManager;



public class Weiterschicken extends Dialog {

	protected Object result;
	protected Shell shell;
	
	private Run run;
	private RunManager runmanager;
	
	private int cwidth;
	private int cheight;
	
	public static void main(String args[]) throws Exception{
		Injector injector = Guice.createInjector(new LocalModule(), new TestDBMemoryFilled());
		RunManager rm = injector.getInstance(RunManager.class);
		UserManager um = injector.getInstance(UserManager.class);
		Run run = rm.getAcceptableRuns(um.getUserById(184)).get(0);
		rm.acceptRun(run, um.getUserById(184));
		
		Weiterschicken w = new Weiterschicken(new Shell(), 0, run, rm);
		w.open();
	}
	
	private ArrayList<EdgeButton> buttons = new ArrayList<EdgeButton>();

	/**
	 * Create the dialog
	 * @param parent
	 * @param style
	 */
	public Weiterschicken(Shell parent, int style, Run run, RunManager runmanager) {
		super(parent, style);
		
		this.run = run;
		this.runmanager = runmanager;
	}

	/**
	 * Create the dialog
	 * @param parent
	 * @param run
	 * @param runmanager
	 */
	public Weiterschicken(Shell parent, Run run, RunManager runmanager) {
		this(parent, SWT.NONE, run, runmanager);
	}

	/**
	 * Open the dialog
	 * @return the result
	 */
	public Object open() {
		createContents();
		shell.open();
		shell.layout();
		Display display = getParent().getDisplay();
		while (!shell.isDisposed()) {
			if (!display.readAndDispatch())
				display.sleep();
		}
		return result;
	}

	/**
	 * Create contents of the dialog
	 */
	protected void createContents() {
		shell = new Shell(getParent(), SWT.APPLICATION_MODAL | SWT.TITLE | SWT.BORDER | SWT.CLOSE);
		shell.setMinimumSize(new Point(274, 368));
		shell.setLayout(new FormLayout());
		shell.setSize(274, 368);
		shell.setText("Kriterienauswahl");
		final Display display = Display.getCurrent();
		Image icon = new Image(display, "icons/32/agt_web.png");
		shell.setImage(icon);

		final Label lblFrage = new Label(shell, SWT.BORDER);
		final FormData fd_lblFrage = new FormData();
		fd_lblFrage.bottom = new FormAttachment(0, 62);
		fd_lblFrage.top = new FormAttachment(0, 10);
		fd_lblFrage.right = new FormAttachment(0, 258);
		fd_lblFrage.left = new FormAttachment(0, 10);
		lblFrage.setLayoutData(fd_lblFrage);

		final Button cmdAbort;
		final Button cmdOk;

		final Composite composite = new Composite(shell, SWT.BORDER);
		final FormData fd_composite = new FormData();
		fd_composite.bottom = new FormAttachment(0, 297);
		fd_composite.top = new FormAttachment(0, 68);
		fd_composite.right = new FormAttachment(0, 258);
		fd_composite.left = new FormAttachment(0, 10);
		composite.setLayoutData(fd_composite);
		composite.setRedraw(true);
		/*cwidth = 248;
		cheight = 229;
		composite.addControlListener(new ControlAdapter() {
			public void controlResized(final ControlEvent e) {
				Point p = shell.getSize();
				p.x = p.x + (composite.getSize().x - cwidth);
				p.y = p.y + (composite.getSize().y - cheight);
				shell.setSize(p);
				
				cwidth = composite.getSize().x;
				cheight = composite.getSize().y;
			}
		}); */
		//composite.setLayout(new FillLayout(SWT.VERTICAL));
		final RowLayout rowLayout = new RowLayout(SWT.VERTICAL);
		rowLayout.fill = true;
		composite.setLayout(rowLayout);
		//composite.setLayout(new GridLayout(1, true));
		
		//Custom code starts here
		Node n = run.getNode();
		Conditions c = n.getConditions();
		
		//Frage setzten
		if(run.getNode().getConditions().getEdgeCount() == 1) {
			lblFrage.setText("---Keine Frage definiert---");
		}
		else {
			lblFrage.setText(c.getTitel());
	
			try {
				List<Edge> el = c.getEdges();
				
				//Antworten erstellen
				for(Edge e : el) {
					EdgeButton b = new EdgeButton(composite, SWT.RADIO, e);
					b.setLayoutData(new RowData(238,20));
					b.setText(e.getDescription());
					b.setVisible(true);
					b.setEnabled(true);
					buttons.add(b);
				}
				composite.pack();
				
			} catch(NullPointerException np) { np.printStackTrace(); }
		}

		final Composite composite_1 = new Composite(shell, SWT.NONE);
		final GridLayout gridLayout = new GridLayout();
		gridLayout.numColumns = 2;
		composite_1.setLayout(gridLayout);
		final FormData fd_composite_1 = new FormData();
		fd_composite_1.bottom = new FormAttachment(composite, 50, SWT.BOTTOM);
		fd_composite_1.top = new FormAttachment(composite, 5, SWT.BOTTOM);
		fd_composite_1.right = new FormAttachment(0, 230);
		fd_composite_1.left = new FormAttachment(0, 45);
		composite_1.setLayoutData(fd_composite_1);
		
		cmdOk = new Button(composite_1, SWT.NONE);
		cmdOk.setLocation(10, shell.getSize().y - 58);
		cmdAbort = new Button(composite_1, SWT.NONE);
		cmdAbort.setLocation(60, shell.getSize().y - 58);
		cmdOk.setLayoutData(new GridData(80, SWT.DEFAULT));
		cmdOk.addMouseListener(new MouseAdapter() {
			public void mouseDown(final MouseEvent e) {
				shell.setCursor(new Cursor(Display.getCurrent(), SWT.CURSOR_WAIT));
				try {
					Edge ed = null;
					
					if(run.getNode().getConditions().getEdgeCount() == 1) {
						ed = run.getNode().getConditions().getEdges().get(0);
					}
					else {
						for(EdgeButton b : buttons) {
							if(b.getSelection() == true) {
								ed = b.getEdge();
							}
					}
					}
					System.out.println("Edge: " + ed.getDescription());
					runmanager.moveOn(run, ed);
					File runDir = FileHandler.getRunDir(FileHandler.prepareDir(run.getUser()), run.getId());
					List<Document> docs = new ArrayList<Document>();
					try {
						for(File f : runDir.listFiles()) {
							Document doc = new Document(0, f.getName(), 0, FileByteConverter.fileToByte(f), run);
							docs.add(doc);
						}
						for(File f : runDir.listFiles()) {
							f.delete();
						}
						runDir.delete();
					} catch (IOException e1) {
						// TODO Auto-generated catch block
						e1.printStackTrace();
					}
					runmanager.uploadDocuments(run, docs);
				}  catch(RemoteException re) { re.printStackTrace(); }
				shell.setCursor(new Cursor(Display.getCurrent(), SWT.CURSOR_ARROW));
				shell.close();
			}
		});
		cmdOk.setText("O&K");
		cmdAbort.setLayoutData(new GridData(80, SWT.DEFAULT));
		cmdAbort.addMouseListener(new MouseAdapter() {
			public void mouseDown(final MouseEvent e) {
				//Just close the window and do nothing
				shell.close();
			}
		});
		cmdAbort.setText("Ab&brechen");		
	}
}

class EdgeButton extends Button {
	
	private Edge e;
	
	public EdgeButton(Composite parent, int style, Edge e) {
		super(parent, style);
		this.e = e;
	}
	
	protected void checkSubclass() {
		// Disable the check that prevents subclassing of SWT components
	}

	public Edge getEdge() {
		return e;
	}

	public void setEdge(Edge e) {
		this.e = e;
	}
}
